package com.vitabuybuy.tv.ui.mine.order.after

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityAfterSaleDetailBinding
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.toast.XToast
import com.library.common.util.DateUtil
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.ui.mine.order.after.adapter.CommonImageAdapter
import com.vitabuybuy.tv.ui.mine.order.after.viewmodel.AfterSaleViewModel
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import com.vitabuybuy.tv.utils.EventCode
import kotlinx.android.synthetic.main.activity_after_sale_detail.*

class AfterSaleDetailActivity : BaseActivity<AfterSaleViewModel, ActivityAfterSaleDetailBinding>() {

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_after_sale_detail

    private var orderId: Int? = 0
    private val imageAdapter by lazy { CommonImageAdapter() }
    override fun onGetBundle(bundle: Bundle?) {
        orderId = bundle?.getInt("orderId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.after_sale_detail))
        mBinding.viewModel = viewModel
        rcImage.apply {
            adapter = imageAdapter
            layoutManager = GridLayoutManager(mContext, 4)
            isNestedScrollingEnabled = false
        }
    }

    override fun observeData() {
        viewModel.getAfterSaleDetail(orderId)
        viewModel.detail.observe(this, Observer {
            setUpBtnView()
            when (it.status) {
                "待买家处理" -> {
                    tvTime.text = String.format(
                        getString(R.string.haisheng),
                        DateUtil.formatSeconds(it.remainingTime)
                    )
                }
                else -> {
                    tvTime.text = it.createTime
                }
            }
            when (it.status) {
                "售后成功" -> {
                    tvStatus.text = it.type + getString(R.string.refund_success)
                    rlAmount.visibility = View.VISIBLE
                    ll_reson.visibility = View.GONE
                    rlRoute.visibility = View.VISIBLE
                    rlArea.visibility = View.GONE
                }
                "售后失败", "售后关闭" -> {
                    tvStatus.text = it.type + getString(R.string.refund_failed)
                    rlAmount.visibility = View.GONE
                    ll_reson.visibility = View.VISIBLE
                    rlRoute.visibility = View.GONE
                    rlArea.visibility = View.GONE
//                    if (it.type == getString(R.string.return_goods_money)) {
//                        tvName.text = it.recipientName
//                        tvPhone.text = it.recipientPhone
//                        tvAddress.text = it.refundAddress
//                    }
                }
                "待审核" -> {
                    tvStatus.text = it.type + getString(R.string.wait_store_audit)
                    rlArea.visibility = View.GONE
                    ll_reson.visibility = View.VISIBLE
                    rlAmount.visibility = View.GONE
                    rlRoute.visibility = View.GONE
                    btnUndoApply.visibility = View.VISIBLE
                    btnModifyApply.visibility = View.VISIBLE
                }
                "待卖家处理" -> {
                    ll_reson.visibility = View.VISIBLE
                    tvStatus.text = it.type + getString(R.string.wait_store_deal)
                    rlArea.visibility = View.GONE
                    rlAmount.visibility = View.GONE
                    rlRoute.visibility = View.GONE
                    btnUndoApply.visibility = View.GONE
                    btnModifyApply.visibility = View.GONE
                }
                "待买家处理" -> {
                    ll_reson.visibility = View.VISIBLE
                    tvStatus.text = it.type + getString(R.string.wait_buyer_deal)
                    rlAmount.visibility = View.GONE
                    rlRoute.visibility = View.GONE
                    btnUndoApply.visibility = View.VISIBLE
                    if (it.type == getString(R.string.return_goods_money)) {
                        tvName.text = it.recipientName
                        tvPhone.text = it.recipientPhone
                        tvAddress.text = it.refundAddress
                        rlArea.visibility = View.VISIBLE
                    } else {
                        rlArea.visibility = View.GONE
                    }
                    if (it.type == getString(R.string.return_goods_money)) {
                        btnHaveSent.visibility = View.VISIBLE
                    }
                }
            }
            if (it.images.isNotEmpty()) {
                imageAdapter.setNewData(it.images.split(","))
            } else {
                rcImage.visibility = View.GONE
            }
        })
    }

    private fun setUpBtnView() {
        btnUndoApply.visibility = View.GONE
        btnModifyApply.visibility = View.GONE
        btnHaveSent.visibility = View.GONE
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            btnContactCustomerService, btnUndoApply,
            btnModifyApply, btnHaveSent, rlNegotiationHistory
        ){v->
            when (v) {
                rlNegotiationHistory -> {
                    NegotiationHistoryActivity.openActivity(mContext, orderId)
                }
                btnContactCustomerService -> {
                    viewModel.detail.value?.run {
                        val chatInfo = ChatInfo()
                        chatInfo.type = TIMConversationType.C2C
                        chatInfo.id = this.store.id.toString()
                        chatInfo.chatName = this.store.name
                        ChatActivity.openActivity(mContext, chatInfo)
                    }
                }
                btnUndoApply -> {
                    AlertDialog.Builder(mContext)
                        .setTitle(getString(R.string.reminder))
                        .setMessage(getString(R.string.are_you_sure_withdraw_the_application))
                        .setCancelable(true)
                        .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                            viewModel.withdrawTheApplication(orderId)
                        }
                        .setNegativeButton(getString(R.string.cancel), null).create().show()

                }
                btnModifyApply -> {
                    var type = if (viewModel.detail.value?.type == "退货退款") {
                        RequestRefundActivity.AFTER_SALE_TYPE_BY_RETURN_GOODS_AND_RETUAN_MONEY
                    } else {
                        RequestRefundActivity.AFTER_SALE_TYPE_BY_ONLY_RETUAN_MONEY
                    }
                    viewModel.detail.value?.run {
                        RequestRefundActivity.openActivity(
                            mContext,
                            this.item,
                            this.id,
                            type
                        )
                    }
                }
                btnHaveSent -> {
                    EditLogisticsActivity.openActivity(mContext, orderId)
                }
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            2 -> {
                XToast.success(getString(R.string.operate_success))
                viewModel.getAfterSaleDetail(orderId)
            }
        }
    }

    override fun onEvent(event: MessageEvent) {
        when (event.code) {
            EventCode.update_after_sale_order_detail -> {
                viewModel.getAfterSaleDetail(orderId)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 1001) {
            viewModel.getAfterSaleDetail(orderId)
        }
    }


    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, orderId: Int) {
            mContext.startActivity(
                bundleOf(Pair("orderId", orderId)),
                AfterSaleDetailActivity::class.java
            )
        }
    }
}
